package com.example.wan_android.viewmodel

import android.content.Intent
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.wan_android.http.bean.SearchInfoBeanData
import com.example.wan_android.http.code.SearchRepository
import com.example.wan_android.ui.activity.WebActivity
import kotlinx.coroutines.launch

class SearchResultViewModel : BaseViewModel() {
    companion object {
        var searchWord = "searchWord"
        var title = "title"
    }

    private val _contentLiveData = MutableLiveData<Result<List<SearchInfoBeanData>>>()
    val contentLiveData = _contentLiveData
    var mTitle = ""
    var mSearchWord = ""
    private var index = 0
    private val _isSuccess = MutableLiveData<Boolean>(false)
    val isSuccess = _isSuccess


    fun getResultData() {
        viewModelScope?.launch {
            SearchRepository().fetchSearch(index, mSearchWord).let { result ->
                if (result.isSuccess) {
                    result.getOrNull()?.let { data ->
                        if (data.isNotEmpty()) {
                            index += 1 // 自动递增页码
                        }
                    }
                }
                _contentLiveData.value = result
                _isSuccess.value = true
            }
        }
    }

    fun openWeb(url: String) {
        startActivity(Intent().apply {
            putExtra(WebViewModel.url, url)
        }, targetClass = WebActivity::class.java)
    }
}